import collections
import time
import calendar
from django.shortcuts import render
from django.http import JsonResponse
from django.db.models import Count
from apps.web import models
import datetime


def dashboard(request, project_id):
    """概览"""
    # 问题数据处理
    status_dict = {}
    for key, text in models.Issues.status_choices:
        status_dict[key] = {'text': text, 'count': 0}
    issues_data = models.Issues.objects.filter(project_id=project_id).values('status').annotate(ct=Count('id'))
    for item in issues_data:
        status_dict[item['status']]['count'] = item['ct']

    # 项目成员
    user_list = models.ProjectUser.objects.filter(project_id=project_id).values_list('user_id', 'user__username')
    # 获取前十个指派任务
    top_ten = models.Issues.objects.filter(project_id=project_id, assign__isnull=False).order_by('-id')[0:10]

    context = {
        'status_dict': status_dict,
        'user_list': user_list,
        'top_ten': top_ten,
    }
    return render(request, 'web/dashboard.html', context)


def issues_chart(request, project_id):
    """图表生成"""
    '''
        最近30天，每天的问题数量
        1.查询近30天的所有数据
        2.对数据进行按日期分组
        3.分好组计数
    '''
    current_time = datetime.datetime.now().date()

    # 创建一个有序字典
    date_dict = collections.OrderedDict()
    # 创建近30天的默认字典
    """
    {
        2025-10-23: [124343556767, 0]
        2025-10-23: [124343556767, 0]
        2025-10-23: [124343556767, 0]
    }
    """
    # # 1. 计算明天
    # tomorrow = current_time + datetime.timedelta(days=1)
    # date_dict[tomorrow.strftime('%Y-%m-%d')] = [time.mktime(tomorrow.timetuple()) * 1000, 0]
    for i in range(0, 31):
        date = current_time - datetime.timedelta(days=i)
        # 构建字典  time.mktime(date.timetuple())转换为时间戳 使用了utc
        date_dict[date.strftime('%Y-%m-%d')] = [calendar.timegm(date.timetuple()) * 1000, 0]

    print(date_dict)
    # select id ,name, DATE_FORMAT(web_issues.create_datetime,"%%Y-%%M-%%D") as ctime from  web_issues
    # id name ctime
    # 1 xxl   2020-3-4

    result = models.Issues.objects.filter(project_id=project_id,
                                          create_datetime__gte=current_time - datetime.timedelta(days=30)).extra(
        select={'ctime': 'DATE_FORMAT(web_issues.create_datetime,"%%Y-%%m-%%d")'}
    ).values('ctime').annotate(ct=Count(id))
    print(result)
    for item in result:
        date_dict[item['ctime']][1] = item['ct']

    # 4. 关键：对列表进行排序 (按时间戳，即 [0] 索引)
    #    使其变为升序，从 10-23 到 11-23
    final_data_list = list(date_dict.values())
    final_data_list.sort(key=lambda item: item[0])
    print(list(date_dict.values()))
    return JsonResponse({'status': True, 'data': final_data_list})
